<?php

/**
 * Application preparation
 *
 * Should be included at the start of all Shopalong scripts
 *
 * Shopalong, the open source shopping system
 * http://shopalong.blogspot.com/
 *
 * @author Stuart Metcalfe <shoopdev@gmail.com>
 * @copyright Copyright &copy; 2003 osCommerce
 * @copyright Portions Copyright &copy; 2006, Shopalong
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */

require_once(dirname(__FILE__).'/configure.php');

// Redirect to install directory if configuration isn't complete
if (strlen(DB_SERVER) < 1)
{
	if (is_dir('install'))
	{
		header('Location: install/index.php');
	}
}

/**
 * Load a local version of the current script.  This allows developers to
 * override the functionality of a supplied script without affecting the
 * upgrade process by placing a new script of the same name in DIR_FS_LOCAL.
 * This only applies to scripts in the main catalog directory.
 * Overriding files should still require() application_top.php and
 * application_bottom.php in order to function properly.  Other than the
 * system configuration file, no constants have been defined at this point.
 */

if (!defined('INLOCAL') && !eregi('^'.DIR_FS_LOCAL, $_SERVER['SCRIPT_FILENAME']))
{
	$path = explode('/', $_SERVER['SCRIPT_FILENAME']);
	$localVersion = DIR_FS_LOCAL.$path[sizeof($path)-1];
	
	if (file_exists($localVersion))
	{
		define('INLOCAL', ''); // Prevent infinite loops
		include($localVersion);
		exit(0);
	}
}

// Some initial constants
error_reporting(E_ALL & ~E_NOTICE);
define('PROJECT_NAME', 'Shopalong Pre1');
define('PROJECT_VERSION', 0.1);
define('API_VERSION', 0.1);

// include the various external libraries
require_once(DIR_WS_INCLUDES.'database_tables.php');
require_once(DIR_WS_INCLUDES.'filenames.php');
require_once(DIR_WS_INCLUDES.'smarty/Smarty.class.php');
require_once(DIR_WS_FUNCTIONS.'compatibility.php');
require_once(DIR_WS_FUNCTIONS.'database.php');
require_once(DIR_WS_FUNCTIONS.'general.php');
require_once(DIR_WS_FUNCTIONS.'general.functions.php');
require_once(DIR_WS_FUNCTIONS.'html_output.php');
require_once(DIR_WS_FUNCTIONS.'password_funcs.php');
require_once(DIR_WS_FUNCTIONS.'template.functions.php');
require_once(DIR_WS_FUNCTIONS.'validations.php');
require_once(DIR_WS_CLASSES.'Account.class.php');
require_once(DIR_WS_CLASSES.'AddressBook.class.php');
require_once(DIR_WS_CLASSES.'Catalog.class.php');
require_once(DIR_WS_CLASSES.'CatalogModule.class.php');
require_once(DIR_WS_CLASSES.'Currencies.class.php');
require_once(DIR_WS_CLASSES.'email.php');
require_once(DIR_WS_CLASSES.'EventManager.class.php');
require_once(DIR_WS_CLASSES.'FormObserver.class.php');
require_once(DIR_WS_CLASSES.'Language.class.php');
require_once(DIR_WS_CLASSES.'MessageStack.class.php');
require_once(DIR_WS_CLASSES.'mime.php');
require_once(DIR_WS_CLASSES.'NavigationHistory.class.php');
require_once(DIR_WS_CLASSES.'Order.class.php');
require_once(DIR_WS_CLASSES.'Product.class.php');
require_once(DIR_WS_CLASSES.'Session.class.php');
require_once(DIR_WS_CLASSES.'ShopalongPlugin.class.php');
require_once(DIR_WS_CLASSES.'ShoppingCart.class.php');
require_once(DIR_WS_CLASSES.'SplitPageResults.class.php');
require_once(DIR_WS_CLASSES.'Theme.class.php');
require_once(DIR_WS_CLASSES.'ValidTypesCommon.class.php');
require_once(DIR_WS_CLASSES.'ValidTypesShopalong.class.php');

// Set the type of request (secure or not)
define('REQUEST_TYPE', (getenv('HTTPS') == 'on') ? 'SSL' : 'NONSSL');

if (REQUEST_TYPE == 'NONSSL')
{
	define('DIR_WS_CATALOG', DIR_WS_HTTP_CATALOG);
}

else
{
	define('DIR_WS_CATALOG', DIR_WS_HTTPS_CATALOG);
}

// Set php_self in the local scope
if (!isset($PHP_SELF))
{
	$PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
}

// PHP5 doesn't seem to use HTTP_GET_VARS or HTTP_POST_VARS any more
if (isset($_GET)) {
	$HTTP_GET_VARS = $_GET;
}

if (isset($_POST)) {
	$HTTP_POST_VARS = $_POST;
}

// The new event manager and register system events
$eventManager = new EventManager();
$eventManager->registerEvent('ProgramStarting', 'onProgramStarting');
$eventManager->registerEvent('ProgramStarted', 'onProgramStarted');
$eventManager->registerEvent('OutputStarting', 'onOutputStarting');
$eventManager->registerEvent('OutputStarted', 'onOutputStarted');
$eventManager->registerEvent('FormSubmitted', 'onFormSubmitted');
$eventManager->registerEvent('OutputEnding', 'onOutputEnding');
$eventManager->registerEvent('OutputEnded', 'onOutputEnded');
$eventManager->registerEvent('ProgramEnding', 'onProgramEnding');
sal_loadPlugins(); // Load plugins
$eventManager->fireEvent('ProgramStarting');

/**
 * @todo Move this to a database abstraction class
 */

// make a connection to the database... now
tep_db_connect() or die('Unable to connect to database server!');

/**
 * @todo Move this to a config class
 */

// set the application parameters
$configuration_query = tep_db_query('select configuration_key as cfgKey, configuration_value as cfgValue from ' . TABLE_CONFIGURATION);

while ($configuration = tep_db_fetch_array($configuration_query))
{
	define($configuration['cfgKey'], $configuration['cfgValue']);
}

// Create new primary objects
$session = new Session();
$account = new Account();
$catalog = new Catalog();
$cart = new ShoppingCart();
$currencies = new Currencies();
$lng = new Language();
$messageStack = new MessageStack();
$navigation = new NavigationHistory();
$navigation->addCurrentPage();

// Process a request to change the language
if (isset($HTTP_GET_VARS['language']) && tep_not_null($HTTP_GET_VARS['language']))
{
	$lng->setLanguage($HTTP_GET_VARS['language']);
}

// Process a request to change the currency
if (isset($HTTP_GET_VARS['currency']))
{
	$currencies->setCurrency($HTTP_GET_VARS['currency']);
}

// include the language translations php file
//require_once(DIR_WS_LANGUAGES . $language . '/default.php');
require_once(DIR_FS_LANGUAGES.'/en/default.php');

/**
 * @todo This should either be moved to the Specials module or a specials plugin
 * which activates on the 'onProgramStarted' event.
 */

// auto expire special products
require_once(DIR_WS_FUNCTIONS . 'specials.php');
tep_expire_specials();

// calculate category path
if (isset($HTTP_GET_VARS['cPath']))
{
	$cPath = $HTTP_GET_VARS['cPath'];
}

elseif (isset($HTTP_GET_VARS['products_id']) && !isset($HTTP_GET_VARS['manufacturers_id']))
{
	$cPath = tep_get_product_path($HTTP_GET_VARS['products_id']);
}

else
{
	$cPath = '';
}

if (tep_not_null($cPath))
{
	$cPath_array = tep_parse_category_path($cPath);
	$cPath = implode('_', $cPath_array);
	$current_category_id = $cPath_array[(sizeof($cPath_array)-1)];
}

else
{
	$current_category_id = 0;
}

// set which precautions should be checked
define('WARN_INSTALL_EXISTENCE', 'true');
define('WARN_CONFIG_WRITEABLE', 'true');
define('WARN_SESSION_DIRECTORY_NOT_WRITEABLE', 'true');
define('WARN_SESSION_AUTO_START', 'true');
define('WARN_DOWNLOAD_DIRECTORY_NOT_READABLE', 'true');

// check if the 'install' directory exists, and warn of its existence
if (WARN_INSTALL_EXISTENCE == 'true')
{
	if (file_exists(dirname($HTTP_SERVER_VARS['SCRIPT_FILENAME']) . '/install'))
	{
		$messageStack->add('header', WARNING_INSTALL_DIRECTORY_EXISTS, 'warning');
	}
}

// check if the configure.php file is writeable
if (WARN_CONFIG_WRITEABLE == 'true')
{
	if ( (file_exists(dirname($HTTP_SERVER_VARS['SCRIPT_FILENAME']) . '/includes/configure.php')) && (is_writeable(dirname($HTTP_SERVER_VARS['SCRIPT_FILENAME']) . '/includes/configure.php')) )
	{
		$messageStack->add('header', WARNING_CONFIG_FILE_WRITEABLE, 'warning');
	}
}

// check if the session folder is writeable
if (WARN_SESSION_DIRECTORY_NOT_WRITEABLE == 'true')
{
	if (STORE_SESSIONS == '')
	{
		if (!is_dir(tep_session_save_path()))
		{
			$messageStack->add('header', WARNING_SESSION_DIRECTORY_NON_EXISTENT, 'warning');
		}
		
		elseif (!is_writeable(tep_session_save_path()))
		{
			$messageStack->add('header', WARNING_SESSION_DIRECTORY_NOT_WRITEABLE, 'warning');
		}
	}
}

// check session.auto_start is disabled
if ( (function_exists('ini_get')) && (WARN_SESSION_AUTO_START == 'true') )
{
	if (ini_get('session.auto_start') == '1')
	{
		$messageStack->add('header', WARNING_SESSION_AUTO_START, 'warning');
	}
}

if ( (WARN_DOWNLOAD_DIRECTORY_NOT_READABLE == 'true') && (DOWNLOAD_ENABLED == 'true') )
{
	if (!is_dir(DIR_FS_DOWNLOAD))
	{
		$messageStack->add('header', WARNING_DOWNLOAD_DIRECTORY_NON_EXISTENT, 'warning');
	}
}

$eventManager->fireEvent('ProgramStarted');

// Initialise the theme
$theme = new Theme();
$theme->assign_by_ref('account', $account);
$theme->assign_by_ref('cart', $cart);
$theme->assign_by_ref('catalog', $catalog);
$theme->assign_by_ref('currencies', $currencies);
$theme->assign_by_ref('language', $lng);
$theme->assign_by_ref('messageStack', $messageStack);
$theme->assign_by_ref('navigation', $navigation);
$theme->assign_by_ref('theme', $theme);

$eventManager->fireEvent('OutputStarting');
$eventManager->fireEvent('OutputStarted');

?>
